package com.football.activity.video;

import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.utils.Log;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.football.R;
import com.football.activity.base.BaseActivity;
import com.football.adapter.MenuAdapter;
import com.football.fragment.news.NewsFragment;
import com.football.fragment.news.VideoViewBuffer;
import com.football.model.WebAddress;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class ScreenActivity extends BaseActivity {

	private static final String VIDEO_URL = "http://cdn4.iptv.oiv.hr:1935/hrtlive/smil:hrt1.smil/playlist.m3u8";
	/** The current activities configuration used to test screen orientation. */
	View app;
	WebView webview;
	ViewGroup tabBar;
	SlidingMenu menu;
	ImageButton btnSlide;
	TextView currentWatching;
	ImageView settingBtn;
	private static final int RESULT_SETTINGS = 1;
	// slider
	MenuAdapter menuAdapter;
	ArrayList<WebAddress> address = new ArrayList<WebAddress>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (!LibsChecker.checkVitamioLibs(this)) {
			return;
		}
		LayoutInflater inflater = LayoutInflater.from(this);
		app = inflater.inflate(R.layout.activity_screen, null);
		setContentView(app);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		tabBar = (ViewGroup) app.findViewById(R.id.tabBar);
		currentWatching = (TextView) app.findViewById(R.id.current_watching);

		// Create a sliding menu getting current activity as context
		menu = new SlidingMenu(this);
		// Set menu mode to appear in the left side of the screen
		menu.setMode(SlidingMenu.LEFT);
		// Disable touch mode to swipe from left to right
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		// Attach menu to this activity, using SLIDING_CONTENT mode
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		// Set menu layout to inflate and use
		menu.setMenu(R.layout.horz_scroll_menu);
		menu.setFadeDegree(0.75f);
		address.addAll(generateWebAddress());
		menuAdapter = new MenuAdapter(this, R.layout.link, address);
		ListView listView = (ListView) menu.findViewById(R.id.list);
		// ViewUtils.initListView(this, listView, "Menu ", 8,
		// android.R.layout.simple_list_item_1);
		listView.setAdapter(menuAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// your fragment transactions go here
						displayFrame(position);
					}
				}, 200);
			}

		});

		btnSlide = (ImageButton) tabBar.findViewById(R.id.BtnSlide);
		btnSlide.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// toggle the menu in and out of the screen
				menu.toggle(true);
			}
		});
		settingBtn = (ImageView) app.findViewById(R.id.settingBtn);
		settingBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				buildSettings();
			}
		});

		ViewTreeObserver vtObserver = btnSlide.getViewTreeObserver();
		if (vtObserver.isAlive()) {
			vtObserver
					.addOnGlobalLayoutListener(new ButtonOnGlobalLayoutListener(
							btnSlide, menu));
		}
		Fragment fragment = new VideoViewBuffer();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction().addToBackStack(null)
				.replace(R.id.frame_container, fragment).commit();
	}

	public TextView getCurrentWatching() {
		return currentWatching;
	}

	public void setCurrentWatching(TextView currentWatching) {
		this.currentWatching = currentWatching;
	}

	private void displayFrame(int position) {
		// update the main content by replacing fragments
		Fragment fragment = null;
		// In just this one instance, we turn the sensor off
		// Until a different menu item is selected, which re-enables it
		// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		String FRAG_NAME = "NewsFragment";
		switch (position) {
		case 0: {
			fragment = new NewsFragment(this);
			FRAG_NAME = "NewsFragment";
			break;
		}
		case 1: {
			fragment = new VideoViewBuffer();
			FRAG_NAME = "VideoViewBuffer";
			break;
		}
		case 2: {
			// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			fragment = new UserSettingFragment();
			FRAG_NAME = "Settings";
			break;
		}

		default:
			// fragment = new VideoPlayerFragment(this, VIDEO_URL, VIDEO_URL);
			FRAG_NAME = "VideoViewBuffer";
			break;
		}
		if (fragment != null) {
			menu.toggle(true);
			FragmentManager fragmentManager = this.getFragmentManager();
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();
			transaction.replace(R.id.frame_container, fragment, FRAG_NAME);
			transaction.addToBackStack(null);
			transaction.commit();
		}
	}

	public void buildSettings() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Add the buttons
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User clicked OK button
			}
		});
		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});
		// Set other dialog properties

		// Create the AlertDialog
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private List<WebAddress> generateWebAddress() {
		List<WebAddress> list = new ArrayList<WebAddress>();
		WebAddress webAddr1 = new WebAddress("Breaking News", "");
		list.add(webAddr1);
		WebAddress webAddr2 = new WebAddress("Watching", "");
		list.add(webAddr2);
		WebAddress webAddr3 = new WebAddress("Settings", "");
		list.add(webAddr3);
		WebAddress webAddr4 = new WebAddress("List Stadium", "");
		list.add(webAddr4);
		return list;
	}

	/**
	 * In order to get btnSlide width, we need to set OnGlobalLayoutListener for
	 * it. This listener then remove itself from the btnSlide so it won't cause
	 * another event to call itself in a loop.
	 * 
	 * @author bachtn
	 * 
	 */
	static class ButtonOnGlobalLayoutListener implements
			ViewTreeObserver.OnGlobalLayoutListener {

		ImageButton btnSlide;
		SlidingMenu menu;

		public ButtonOnGlobalLayoutListener(ImageButton btnSlide,
				SlidingMenu menu) {
			this.btnSlide = btnSlide;
			this.menu = menu;
		}

		@Override
		public void onGlobalLayout() {
			btnSlide.getViewTreeObserver().removeGlobalOnLayoutListener(this);
			// Set the space left on the right side of the screen when
			// menu slide from left to right
			menu.setBehindOffset(btnSlide.getWidth());
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		VideoViewBuffer videoFragment = (VideoViewBuffer) getFragmentManager()
				.findFragmentByTag("VideoViewBuffer");
		if (videoFragment.isVisible()) {
			// Hide/show status bar
			toggleTabBar();
			if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				videoFragment.getFavoriteChannel()
						.setVisibility(ViewGroup.GONE);
				// videoFragment.getAddStreamArea().setVisibility(ViewGroup.GONE);
				// videoFragment.getmVideoView().setVideoLayout(
				// VideoView.VIDEO_LAYOUT_STRETCH, 0);
				Log.e("On Config Change", "LANDSCAPE");
			} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
				videoFragment.getFavoriteChannel().setVisibility(
						ViewGroup.VISIBLE);
				// videoFragment.getAddStreamArea().setVisibility(
				// ViewGroup.VISIBLE);
				// videoFragment.getmVideoView().setVideoLayout(
				// VideoView.VIDEO_LAYOUT_ORIGIN, 0);
				Log.e("On Config Change", "PORTRAIT");
			}
		}
		// Menu left open is closed
		if (menu.isMenuShowing()) {
			menu.toggle();
		}

	}

	private void toggleTabBar() {
		if (tabBar.getVisibility() == ViewGroup.VISIBLE) {
			tabBar.setVisibility(ViewGroup.GONE);
		} else if (tabBar.getVisibility() == ViewGroup.GONE) {
			tabBar.setVisibility(ViewGroup.VISIBLE);
		}
	}
}
